package com.drinks.yiniang.adapter.goods;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.AppCompatTextView;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseViewHolder;
import com.drinks.yiniang.R;
import com.drinks.yiniang.adapter.base.BaseMultiItemQuickRCVAdapter;
import com.drinks.yiniang.entity.comment.GoodsCommentJson;
import com.drinks.yiniang.entity.common.RadarEntity;
import com.drinks.yiniang.entity.goods.GoodsDetailJson;
import com.drinks.yiniang.entity.goods.GoodsJson;
import com.drinks.yiniang.io.http.HttpUrls;
import com.drinks.yiniang.ui.activity.goods.GoodsCommentsActivity;
import com.drinks.yiniang.ui.widget.layout.DimensionWrapLayout;
import com.drinks.yiniang.ui.widget.layout.ParamsTableLayout;
import com.drinks.yiniang.ui.widget.textview.TagTextView;
import com.drinks.yiniang.ui.widget.view.RadarMapView;
import com.drinks.yiniang.utils.GlideUtils;
import com.hansen.library.Constants;
import com.hansen.library.listener.CheckDoubleClickListener;
import com.hansen.library.ui.widget.image.CircleImageView;
import com.hansen.library.ui.widget.image.RatioRoundImageView;
import com.hansen.library.ui.widget.image.SquareImageView;
import com.hansen.library.ui.widget.layout.AutoLineFeedLayout;
import com.hansen.library.ui.widget.ratingbar.CustomRatingBar;
import com.hansen.library.utils.ColorUtils;
import com.hansen.library.utils.CommonUtils;
import com.hansen.library.utils.ScreenSizeUtils;
import com.hansen.library.utils.StringUtils;

import java.util.ArrayList;
import java.util.List;

import static com.drinks.yiniang.entity.goods.GoodsDetailJson.ITEM_TYPE_GOODS_COMMENT;
import static com.drinks.yiniang.entity.goods.GoodsDetailJson.ITEM_TYPE_GOODS_RECOMMENT_LIST;
import static com.drinks.yiniang.entity.goods.GoodsDetailJson.ITEM_TYPE_GOODS_RECOMMENT_TITLE;
import static com.drinks.yiniang.entity.goods.GoodsDetailJson.ITEM_TYPE_GOODS_WEB;

/**
 * 商品详情adapter
 *
 * @author han
 * @date 2019/8/30
 */
public class GoodsDetailAdapter extends BaseMultiItemQuickRCVAdapter<GoodsDetailJson.GoodsDetailList, BaseViewHolder> {

    private ViewGroup.LayoutParams paramsField;

    private TagTextView mTagTextView;

    private StringBuilder mBuilder;

    private Drawable mLikeFocusDrawable;
    private Drawable mLikeNormalDrawable;

    private WebView mWebView;

    private List<RadarEntity> mRadarList;
    private RadarEntity mRadarEntity;

    private int dp8;

    public GoodsDetailAdapter(Context mContext, @Nullable List<GoodsDetailJson.GoodsDetailList> data) {
        super(data);

        addItemType(ITEM_TYPE_GOODS_COMMENT, R.layout.item_goods_detail_comment);
        addItemType(ITEM_TYPE_GOODS_WEB, R.layout.item_goods_detail_web);
        addItemType(ITEM_TYPE_GOODS_RECOMMENT_TITLE, R.layout.item_goods_detail_recomment_title);
        addItemType(ITEM_TYPE_GOODS_RECOMMENT_LIST, R.layout.item_home_goods);

        mLikeFocusDrawable = ContextCompat.getDrawable(mContext, R.mipmap.icon_comment_praise_like);
        mLikeNormalDrawable = ContextCompat.getDrawable(mContext, R.mipmap.icon_comment_praise_normal);

        paramsField = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, ScreenSizeUtils.dp2px(mContext, 20));

        dp8 = ScreenSizeUtils.dp2px(mContext, 8);
    }

    @Override
    protected void convert(BaseViewHolder helper, GoodsDetailJson.GoodsDetailList item) {
        switch (helper.getItemViewType()) {
            case ITEM_TYPE_GOODS_COMMENT://评论
                setCommentAndParamsData(helper, item);
                //专家领域
                addFields((AutoLineFeedLayout) helper.getView(R.id.ll_goods_detail_comments_field), item.getTempComment());

                helper.addOnClickListener(R.id.tv_goods_detail_comment_all);
                break;
            case ITEM_TYPE_GOODS_WEB://商品详情web
                setGoodsContent((FrameLayout) helper.getView(R.id.fl_goods_detail_web), item.getTempGoodsContent());
                helper.addOnClickListener(R.id.btn_goods_detail_join);
                break;
            case ITEM_TYPE_GOODS_RECOMMENT_LIST://推荐商品
                mBuilder = new StringBuilder();

                GlideUtils.loadGoodsList(mContext, (RatioRoundImageView) helper.getView(R.id.iv_home_goods_cover), item.getCover_url());

                //活动tag
                addLabelTag((AutoLineFeedLayout) helper.getView(R.id.ll_home_goods_label), item.getActivity());

                //商品名称
                helper.setText(R.id.tv_home_goods_name, item.getName());
                //推荐语
                helper.setText(R.id.tv_home_goods_slogan, item.getRecommend_reason());
                //价格
                mBuilder = new StringBuilder();
                mBuilder.append("¥");
                mBuilder.append(StringUtils.getGoodsPrice(item.getApp_price(), item.getActivity_price()));
                helper.setText(R.id.tv_home_goods_price, mBuilder);

                helper.addOnClickListener(R.id.iv_home_goods_add_cart);
                break;
            default:
                break;
        }
    }

    private void addLabelTag(AutoLineFeedLayout layout, List<GoodsJson.GoodsActivity> actList) {
        layout.removeAllViews();

        if (CommonUtils.isEmptyList(actList)) {
            layout.setVisibility(View.GONE);

            return;
        }

        layout.setVisibility(View.VISIBLE);

        for (GoodsJson.GoodsActivity data : actList) {
            mTagTextView = new TagTextView(mContext);
            mTagTextView.setTagColor(data.getTag_color());
            mTagTextView.setText(data.getTag_name());

            layout.addView(mTagTextView);
        }
    }

    //设置评论数据
    private void setCommentAndParamsData(BaseViewHolder helper, final GoodsDetailJson.GoodsDetailList item) {
        //总的评论数
        mBuilder = new StringBuilder(StringUtils.getNullEmptyConvertZero(item.getTempCommentCount()));
        mBuilder.append("条");
        helper.setText(R.id.tv_goods_detail_comment_num, mBuilder);

        //暂无评论
        if (item.getTempComment() == null) {
            helper.setVisible(R.id.iv_goods_detail_evaluate_avatar, false);
            helper.setVisible(R.id.tv_goods_detail_comment_nickname, false);
            helper.setVisible(R.id.rating_goods_detail_comment, false);
            helper.setVisible(R.id.tv_goods_detail_comment_content, false);
            helper.setVisible(R.id.tv_goods_detail_comment_time, false);
            helper.setVisible(R.id.tv_goods_detail_comment_praise, false);

            helper.setGone(R.id.tv_goods_detail_no_comment, true);
        } else {
            helper.setVisible(R.id.iv_goods_detail_evaluate_avatar, true);
            helper.setVisible(R.id.tv_goods_detail_comment_nickname, true);
            helper.setVisible(R.id.rating_goods_detail_comment, true);
            helper.setVisible(R.id.tv_goods_detail_comment_content, true);
            helper.setGone(R.id.tv_goods_detail_no_comment, false);

            GlideUtils.loadAvatar(mContext, (CircleImageView) helper.getView(R.id.iv_goods_detail_evaluate_avatar), item.getTempComment().getAvatar());
            helper.setText(R.id.tv_goods_detail_comment_nickname, item.getTempComment().getUsername());
            helper.setText(R.id.tv_goods_detail_comment_content, item.getTempComment().getContent());

            CustomRatingBar ratingBar = helper.getView(R.id.rating_goods_detail_comment);
            ratingBar.setStar(item.getTempComment().getScore());

            if (CommonUtils.getListSize(item.getTempComment().getRadar()) >= 5) {//专家点评
                helper.setVisible(R.id.tv_goods_detail_comment_time, false);
                helper.setVisible(R.id.tv_goods_detail_comment_praise, false);

                helper.setGone(R.id.iv_gd_comments_radar_map, true);
                helper.setGone(R.id.lv_gd_comments_star, true);
                helper.setGone(R.id.tv_gd_all_expert_comment, true);

                //雷达图
                setRadarData((ImageView) helper.getView(R.id.iv_gd_comments_radar_map), (DimensionWrapLayout) helper.getView(R.id.lv_gd_comments_star), item.getTempComment());
                helper.addOnClickListener(R.id.tv_gd_all_expert_comment);
            } else {
                helper.setGone(R.id.iv_gd_comments_radar_map, false);
                helper.setGone(R.id.lv_gd_comments_star, false);
                helper.setGone(R.id.tv_gd_all_expert_comment, false);

                helper.setVisible(R.id.tv_goods_detail_comment_time, true);
                helper.setVisible(R.id.tv_goods_detail_comment_praise, true);

                TextView tvLike = helper.getView(R.id.tv_goods_detail_comment_praise);

                helper.setText(R.id.tv_goods_detail_comment_time, item.getTempComment().getCreated_at());
                helper.setText(R.id.tv_goods_detail_comment_praise, StringUtils.getNullEmptyConvertZero(item.getTempComment().getLike_count()));

                tvLike.setCompoundDrawablesWithIntrinsicBounds(null, null, Constants.STATUS_GLOBAL_YES.equals(item.getTempComment().getIs_like()) ? mLikeFocusDrawable : mLikeNormalDrawable, null);
                tvLike.setSelected(Constants.STATUS_GLOBAL_YES.equals(item.getTempComment().getIs_like()));
            }
        }

        //设置参数
        final ParamsTableLayout tabLayout = helper.getView(R.id.ll_goods_detail_param_table);
        final TextView tvAllParams = helper.getView(R.id.tv_goods_detail_expand_all);

        if (item.isShowAllParams()) {
            tabLayout.addAllParamsView();
            tvAllParams.setVisibility(View.GONE);
        } else {
            tabLayout.addParamsTabData(item.getTempParams());
            tvAllParams.setVisibility(CommonUtils.getListSize(item.getTempParams()) > tabLayout.getShowStepMax() ? View.VISIBLE : View.GONE);
        }

        helper.setGone(R.id.tv_goods_detail_no_params, CommonUtils.getListSize(item.getTempParams()) <= 0);

        tvAllParams.setOnClickListener(new CheckDoubleClickListener() {
            @Override
            public void onCheckDoubleClick(View v) {
                item.setShowAllParams(true);
                tabLayout.addAllParamsView();
                tvAllParams.setVisibility(View.GONE);
            }
        });
    }

    private void setRadarData(ImageView mRadarMapView, DimensionWrapLayout layout, GoodsDetailJson.GoodsDetailComments comments) {
        mRadarList = new ArrayList<>();

        for (GoodsCommentJson.GoodsCommentRadar radar : comments.getRadar()) {
            mRadarEntity = new RadarEntity(radar.getName(), StringUtils.getFloat(radar.getValue()));
            mRadarList.add(mRadarEntity);
        }

        GlideUtils.loadSquareImage(mContext, mRadarMapView, comments.getRadar_map_url());

        //mRadarMapView.setRadarEvaluateData(mRadarList, 5);

        //雷达图对应的星级
        layout.addGoodsCommentsDimensionLayout(comments.getRadar());
    }

    //添加领域
    private void addFields(AutoLineFeedLayout feedLayout, GoodsDetailJson.GoodsDetailComments comments) {
        feedLayout.removeAllViews();

        if (comments == null || CommonUtils.isEmptyList(comments.getSkill())) {
            return;
        }

        //动态添加属性值
        for (int i = 0; i < comments.getSkill().size(); i++) {
            final AppCompatTextView tvAttrsValueView = getAttrsTextView();

            tvAttrsValueView.setText(comments.getSkill().get(i));

            feedLayout.addView(tvAttrsValueView, paramsField);
        }
    }

    private AppCompatTextView getAttrsTextView() {
        AppCompatTextView tv = new AppCompatTextView(mContext);

        tv.setTextColor(ColorUtils.getColorById(mContext, R.color.color_ef3024));
        tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
        tv.setBackgroundResource(R.drawable.shape_bkg_specialist_field);
        tv.setPadding(dp8, 0, dp8, 0);
        tv.setGravity(Gravity.CENTER_VERTICAL);

        return tv;
    }

    //设置商品富文本数据
    private void setGoodsContent(FrameLayout fl, String content) {
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        fl.removeAllViews();

        if (mWebView == null) {
            initWebView();
        }

        fl.addView(mWebView, params);

        mWebView.loadDataWithBaseURL(HttpUrls.API_HOST, StringUtils.getNullEmptyConvertNone(content), "text/html", "utf-8", null);
    }

    private void initWebView() {
        mWebView = new WebView(mContext);

        mWebView.setBackgroundColor(0);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); //取消滚动条白边效果
        mWebView.getSettings().setDefaultTextEncodingName("UTF-8");
        mWebView.getSettings().setBlockNetworkImage(false);
        mWebView.getSettings().setDomStorageEnabled(true);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWebView.getSettings().setMixedContentMode(mWebView.getSettings().MIXED_CONTENT_ALWAYS_ALLOW);  //注意安卓5.0以上的权限
        }

        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }
        });
    }

    public void destroyWebview() {
        if (mWebView != null) {
            mWebView.stopLoading();
            mWebView.clearHistory();
            //webview.pauseTimers();
            mWebView.setWebChromeClient(null);
            mWebView.destroy();
            mWebView = null;
        }
    }
}
